package com.vmladenov.cook.ui.recipes;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.vmladenov.cook.R;
import com.vmladenov.cook.core.html.SmallPreview;
import com.vmladenov.cook.core.loaders.RecipesLoader;
import com.vmladenov.cook.ui.PagedListActivity;

public final class AllRecipesActivity extends PagedListActivity<RecipesLoader>
{
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		this.setTitle(R.string.allRecipesLong);
	}

	@Override
	public boolean onSearchRequested()
	{
		startSearch(null, false, null, false);
		return true;
	}

	@Override
	protected void onListItemClick(ListView parent, View v, int position, long id)
	{
		ListAdapter adapter = getListAdapter();
		SmallPreview item = (SmallPreview) adapter.getItem(position);
		Intent intent = new Intent(this, ViewRecipeActivity.class);
		Bundle bundle = new Bundle();
		bundle.putLong("id", item.id);
		intent.putExtra("RECIPE_ID", bundle);
		startActivity(intent);
	}

	@Override
	protected RecipesLoader CreateLoader()
	{
		return new RecipesLoader();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.recipes_list_menu, menu);
		mainMenu = menu;
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item)
	{
		switch (item.getItemId())
		{
			case R.id.miAlphabetSorting:
				setMenuVisibility(1);
				return true;
			case R.id.miDateSorting:
				setMenuVisibility(2);
				return true;
			case R.id.miRatingSorting:
				setMenuVisibility(3);
				return true;
			default:
				return false;
		}
	}

	private void setMenuVisibility(int miItem)
	{
		MenuItem itemAlphabetSorting = mainMenu.findItem(R.id.miAlphabetSorting);
		MenuItem itemDateSorting = mainMenu.findItem(R.id.miDateSorting);
		MenuItem itemRatingSorting = mainMenu.findItem(R.id.miRatingSorting);
		_loader = CreateLoader();
		switch (miItem)
		{
			case 1:
				itemAlphabetSorting.setVisible(false);
				itemDateSorting.setVisible(true);
				itemRatingSorting.setVisible(true);
				_loader.sorting = 0;
				break;
			case 2:
				itemAlphabetSorting.setVisible(true);
				itemDateSorting.setVisible(false);
				itemRatingSorting.setVisible(true);
				_loader.sorting = 1;
				break;
			case 3:
				itemAlphabetSorting.setVisible(true);
				itemDateSorting.setVisible(true);
				itemRatingSorting.setVisible(false);
				_loader.sorting = 2;
				break;
		}
		loadFirstData();
	}

}
